using System;
using System.Collections;

namespace ManticLabs.Data
{
	public class FilterCriteria
	{
		ArrayList fields;

		public FilterCriteria()
		{
		}

		public void add(string fieldName, object val){
			if(fields == null)
				fields = new ArrayList();
			fields.Add(new Field(fieldName, val));
		}

		public void setField(string fieldName, object val){
			Field field = getFieldObject(fieldName);
			if(val != null && !IsEmptyString(val))
			{
				if(field != null)
					field.Value = val;
				else
					add(fieldName, val);
			}
			else
			{
				if(field != null)
					fields.Remove(field);
			}
		}

		protected bool IsEmptyString(object val)
		{
			if(val is string)
				return val.ToString().Trim().Length <= 0;
			return false;
		}

		public string getField(string fieldName)
		{
			Field field = getFieldObject(fieldName);
			if(field != null)
				return field.StringValue;
			return null;
		}

		public object getFieldValue(string fieldName)
		{
			Field field = getFieldObject(fieldName);
			if(field != null)
				return field.Value;
			return null;
		}


		private Field getFieldObject(string fieldName)
		{
			if(fields != null)
			{
				for(int i=0; i < fields.Count; i++)
				{
					Field field = fields[i] as Field;
					if(field.Name.Equals(fieldName))
						return field;
				}
			}
			return null;
		}

		public ArrayList Fields
		{
			get
			{
				return fields;
			}
		}

		public int Count
		{
			get
			{
				if(fields == null)
					return 0;
				return fields.Count;
			}
		}

		public Field this[int index]
		{
			get
			{
				return fields[index] as Field;
			}
		}

		public class Field
		{
			private string name;
			private object val;

			public Field(){}

			public Field(string name, object val)
			{
                this.name = name;
				this.val = val;
			}

			public string Name
			{
				get
				{
					return name;
				}
				set
				{
					name = value;
				}
			}

			public object Value
			{
				get
				{
					return val;
				}
				set
				{
					val = value;
				}
			}

			public string StringValue
			{
				get
				{
					if(val != null)
						return Convert.ToString(val);
					return null;
				}
			}

			public override bool Equals(object obj)
			{
				if(obj is Field)
					return ((Field)obj).Name.Equals(Name);
				return base.Equals (obj);
			}

            public override int GetHashCode()
            {
                return base.GetHashCode();
            }

        }
	}
}
